/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package kimo.persistence.controllers;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import kimo.persistence.entities.Prefecture;
import kimo.persistence.entities.Producer;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import kimo.persistence.controllers.exceptions.IllegalOrphanException;
import kimo.persistence.controllers.exceptions.NonexistentEntityException;
import kimo.persistence.controllers.exceptions.PreexistingEntityException;
import kimo.persistence.entities.Municipality;

/**
 *
 * @author a381u296
 */
public class MunicipalityJpaController implements Serializable {

    public MunicipalityJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Municipality municipality) throws PreexistingEntityException, Exception {
        if (municipality.getProducerList() == null) {
            municipality.setProducerList(new ArrayList<Producer>());
        }
        if (municipality.getProducerList1() == null) {
            municipality.setProducerList1(new ArrayList<Producer>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Prefecture municipalityPrefectureId = municipality.getMunicipalityPrefectureId();
            if (municipalityPrefectureId != null) {
                municipalityPrefectureId = em.getReference(municipalityPrefectureId.getClass(), municipalityPrefectureId.getPrefectureId());
                municipality.setMunicipalityPrefectureId(municipalityPrefectureId);
            }
            List<Producer> attachedProducerList = new ArrayList<Producer>();
            for (Producer producerListProducerToAttach : municipality.getProducerList()) {
                producerListProducerToAttach = em.getReference(producerListProducerToAttach.getClass(), producerListProducerToAttach.getProducerId());
                attachedProducerList.add(producerListProducerToAttach);
            }
            municipality.setProducerList(attachedProducerList);
            List<Producer> attachedProducerList1 = new ArrayList<Producer>();
            for (Producer producerList1ProducerToAttach : municipality.getProducerList1()) {
                producerList1ProducerToAttach = em.getReference(producerList1ProducerToAttach.getClass(), producerList1ProducerToAttach.getProducerId());
                attachedProducerList1.add(producerList1ProducerToAttach);
            }
            municipality.setProducerList1(attachedProducerList1);
            em.persist(municipality);
            if (municipalityPrefectureId != null) {
                municipalityPrefectureId.getMunicipalityList().add(municipality);
                municipalityPrefectureId = em.merge(municipalityPrefectureId);
            }
            for (Producer producerListProducer : municipality.getProducerList()) {
                Municipality oldProducerRuralMunicipalityIdOfProducerListProducer = producerListProducer.getProducerRuralMunicipalityId();
                producerListProducer.setProducerRuralMunicipalityId(municipality);
                producerListProducer = em.merge(producerListProducer);
                if (oldProducerRuralMunicipalityIdOfProducerListProducer != null) {
                    oldProducerRuralMunicipalityIdOfProducerListProducer.getProducerList().remove(producerListProducer);
                    oldProducerRuralMunicipalityIdOfProducerListProducer = em.merge(oldProducerRuralMunicipalityIdOfProducerListProducer);
                }
            }
            for (Producer producerList1Producer : municipality.getProducerList1()) {
                Municipality oldProducerMunicipalityIdOfProducerList1Producer = producerList1Producer.getProducerMunicipalityId();
                producerList1Producer.setProducerMunicipalityId(municipality);
                producerList1Producer = em.merge(producerList1Producer);
                if (oldProducerMunicipalityIdOfProducerList1Producer != null) {
                    oldProducerMunicipalityIdOfProducerList1Producer.getProducerList1().remove(producerList1Producer);
                    oldProducerMunicipalityIdOfProducerList1Producer = em.merge(oldProducerMunicipalityIdOfProducerList1Producer);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findMunicipality(municipality.getMunicipalityId()) != null) {
                throw new PreexistingEntityException("Municipality " + municipality + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Municipality municipality) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Municipality persistentMunicipality = em.find(Municipality.class, municipality.getMunicipalityId());
            Prefecture municipalityPrefectureIdOld = persistentMunicipality.getMunicipalityPrefectureId();
            Prefecture municipalityPrefectureIdNew = municipality.getMunicipalityPrefectureId();
            List<Producer> producerListOld = persistentMunicipality.getProducerList();
            List<Producer> producerListNew = municipality.getProducerList();
            List<Producer> producerList1Old = persistentMunicipality.getProducerList1();
            List<Producer> producerList1New = municipality.getProducerList1();
            List<String> illegalOrphanMessages = null;
            for (Producer producerListOldProducer : producerListOld) {
                if (!producerListNew.contains(producerListOldProducer)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Producer " + producerListOldProducer + " since its producerRuralMunicipalityId field is not nullable.");
                }
            }
            for (Producer producerList1OldProducer : producerList1Old) {
                if (!producerList1New.contains(producerList1OldProducer)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Producer " + producerList1OldProducer + " since its producerMunicipalityId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (municipalityPrefectureIdNew != null) {
                municipalityPrefectureIdNew = em.getReference(municipalityPrefectureIdNew.getClass(), municipalityPrefectureIdNew.getPrefectureId());
                municipality.setMunicipalityPrefectureId(municipalityPrefectureIdNew);
            }
            List<Producer> attachedProducerListNew = new ArrayList<Producer>();
            for (Producer producerListNewProducerToAttach : producerListNew) {
                producerListNewProducerToAttach = em.getReference(producerListNewProducerToAttach.getClass(), producerListNewProducerToAttach.getProducerId());
                attachedProducerListNew.add(producerListNewProducerToAttach);
            }
            producerListNew = attachedProducerListNew;
            municipality.setProducerList(producerListNew);
            List<Producer> attachedProducerList1New = new ArrayList<Producer>();
            for (Producer producerList1NewProducerToAttach : producerList1New) {
                producerList1NewProducerToAttach = em.getReference(producerList1NewProducerToAttach.getClass(), producerList1NewProducerToAttach.getProducerId());
                attachedProducerList1New.add(producerList1NewProducerToAttach);
            }
            producerList1New = attachedProducerList1New;
            municipality.setProducerList1(producerList1New);
            municipality = em.merge(municipality);
            if (municipalityPrefectureIdOld != null && !municipalityPrefectureIdOld.equals(municipalityPrefectureIdNew)) {
                municipalityPrefectureIdOld.getMunicipalityList().remove(municipality);
                municipalityPrefectureIdOld = em.merge(municipalityPrefectureIdOld);
            }
            if (municipalityPrefectureIdNew != null && !municipalityPrefectureIdNew.equals(municipalityPrefectureIdOld)) {
                municipalityPrefectureIdNew.getMunicipalityList().add(municipality);
                municipalityPrefectureIdNew = em.merge(municipalityPrefectureIdNew);
            }
            for (Producer producerListNewProducer : producerListNew) {
                if (!producerListOld.contains(producerListNewProducer)) {
                    Municipality oldProducerRuralMunicipalityIdOfProducerListNewProducer = producerListNewProducer.getProducerRuralMunicipalityId();
                    producerListNewProducer.setProducerRuralMunicipalityId(municipality);
                    producerListNewProducer = em.merge(producerListNewProducer);
                    if (oldProducerRuralMunicipalityIdOfProducerListNewProducer != null && !oldProducerRuralMunicipalityIdOfProducerListNewProducer.equals(municipality)) {
                        oldProducerRuralMunicipalityIdOfProducerListNewProducer.getProducerList().remove(producerListNewProducer);
                        oldProducerRuralMunicipalityIdOfProducerListNewProducer = em.merge(oldProducerRuralMunicipalityIdOfProducerListNewProducer);
                    }
                }
            }
            for (Producer producerList1NewProducer : producerList1New) {
                if (!producerList1Old.contains(producerList1NewProducer)) {
                    Municipality oldProducerMunicipalityIdOfProducerList1NewProducer = producerList1NewProducer.getProducerMunicipalityId();
                    producerList1NewProducer.setProducerMunicipalityId(municipality);
                    producerList1NewProducer = em.merge(producerList1NewProducer);
                    if (oldProducerMunicipalityIdOfProducerList1NewProducer != null && !oldProducerMunicipalityIdOfProducerList1NewProducer.equals(municipality)) {
                        oldProducerMunicipalityIdOfProducerList1NewProducer.getProducerList1().remove(producerList1NewProducer);
                        oldProducerMunicipalityIdOfProducerList1NewProducer = em.merge(oldProducerMunicipalityIdOfProducerList1NewProducer);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = municipality.getMunicipalityId();
                if (findMunicipality(id) == null) {
                    throw new NonexistentEntityException("The municipality with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Municipality municipality;
            try {
                municipality = em.getReference(Municipality.class, id);
                municipality.getMunicipalityId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The municipality with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Producer> producerListOrphanCheck = municipality.getProducerList();
            for (Producer producerListOrphanCheckProducer : producerListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Municipality (" + municipality + ") cannot be destroyed since the Producer " + producerListOrphanCheckProducer + " in its producerList field has a non-nullable producerRuralMunicipalityId field.");
            }
            List<Producer> producerList1OrphanCheck = municipality.getProducerList1();
            for (Producer producerList1OrphanCheckProducer : producerList1OrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Municipality (" + municipality + ") cannot be destroyed since the Producer " + producerList1OrphanCheckProducer + " in its producerList1 field has a non-nullable producerMunicipalityId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Prefecture municipalityPrefectureId = municipality.getMunicipalityPrefectureId();
            if (municipalityPrefectureId != null) {
                municipalityPrefectureId.getMunicipalityList().remove(municipality);
                municipalityPrefectureId = em.merge(municipalityPrefectureId);
            }
            em.remove(municipality);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Municipality> findMunicipalityEntities() {
        return findMunicipalityEntities(true, -1, -1);
    }

    public List<Municipality> findMunicipalityEntities(int maxResults, int firstResult) {
        return findMunicipalityEntities(false, maxResults, firstResult);
    }

    private List<Municipality> findMunicipalityEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Municipality.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Municipality findMunicipality(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Municipality.class, id);
        } finally {
            em.close();
        }
    }

    public int getMunicipalityCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Municipality> rt = cq.from(Municipality.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
